package jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * @Author zhangtao
 * @create 2022/4/28 10:57
 */
public class JwtTest {
    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.now().plusSeconds(1);
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        Date expireDate = Date.from(instant);
        String secret = instant.getEpochSecond() + "000";
        String token = JWT.create()
                .withHeader(new HashMap<>())
                .withClaim("imei", "866960050741451")
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(secret));

        System.out.println(secret);
        secret = JWT.decode(token).getExpiresAt().getTime() + "";
        System.out.println(secret);
        // 创建解析对象，使用的算法和secret要与创建token时保持一致
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        // 解析指定的token
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        // 获取解析后的token中的payload信息
        Claim imei = decodedJWT.getClaim("imei");
        System.out.println(imei.asString());

    }
}
